package com.jic.market.common.base;

import com.alibaba.fastjson.JSON;
import com.jic.common.base.vo.RestResult;
import com.jic.market.common.exception.MarketErrorCodeEnum;
import com.jic.market.common.exception.MarketException;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ValidationException;

/**
 * @author yinhaijun
 * @date: 2020/4/3
 */
@Slf4j
public class MarketBaseController {


    protected <Q> RestResult<Q> executeService(MarketBaseController.Service<Q> service){
        RestResult<Q> result = new RestResult();
        try {
            long start = System.currentTimeMillis();
            //服务调用
            Q data = service.execute();
            result.setCode("0000");
            result.setMsg("成功");
            result.setData(data);
            long end = System.currentTimeMillis();
            log.info("服务返回，用时,{},{}", end - start, JSON.toJSONString(result));
        }catch (ValidationException ve){
            log.info("参数校验异常", ve);
            result.setCode(MarketErrorCodeEnum.PARAM_ERROR.getCode());
            result.setMsg(ve.getMessage());
        }catch (MarketException fe){
            log.info("服务异常", fe);
            result.setCode(fe.getCode());
            result.setMsg(fe.getMessage());
        }catch (Exception e){
            log.info("出现未知异常", e);
            result.setCode("9999");
            result.setMsg("未知异常");
        }
        return result;
    }

    protected interface Service<Q>{
        Q execute();
    }

}
